package com.example.yonghucenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.yonghucenter.common.ErrorCode;
import com.example.yonghucenter.common.ResultUtils;
import com.example.yonghucenter.domain.po.User;
import com.example.yonghucenter.exception.BusinessException;
import com.example.yonghucenter.service.UserService;
import com.example.yonghucenter.mapper.UserMapper;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;

import static com.example.yonghucenter.constent.UserConstent.SALT;
import static com.example.yonghucenter.constent.UserConstent.userLogin;

/**
 * @author LENOVO
 * @description 针对表【user(用户表)】的数据库操作Service实现
 * @createDate 2025-06-01 12:27:14
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword) {
        //1.检验参数是否为空
        if (userAccount == null || userPassword == null || checkPassword == null) {

            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数不能为空");

        }
        //2.账户长度不小于4
        if (userAccount.length() < 4) {

            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账户长度不小于4");
        }
        //3.密码不小于8 位
        if (userPassword.length() < 8 || checkPassword.length() < 8) {

            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码不小于8位");
        }
        // 账户不能重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        long count = userMapper.selectCount(queryWrapper);
        if (count > 0) {

            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账户不能重复");
        }

        //5.账户不能包含特殊字符
        String validPattern = "^[a-zA-Z0-9_]+$";
        if (!userAccount.matches(validPattern)) {

            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账户不能包含特殊字符");
        }
        //6.密码和校验密码相同
        if (!userPassword.equals(checkPassword)) {

            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码和校验密码不相同");
        }
        //7.对密码进行加密（密码千万不要直接以明文存储到数据库中）
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        //8.向数据库插入用户数据 账号密码 创建时间
        //获取当前时间
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setCreateTime(new Date());
        //保存到数据库中
        this.save(user);
        return count;
    }

    /***
     * 用户登陆
     * @param userAccount
     * @param userPassword
     * @param request
     * @return
     */

    @Override
    public User userLogin(String userAccount,  String userPassword, HttpServletRequest request) {

        //2. 账户长度不小于 4 位
        if (userAccount == null || userPassword == null) {
          throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号或者密码不能为空");
        }
         if (userAccount.length() < 4) {
             throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号长度不小于4");

        }
         //3. 密码就不小于 8 位
          if (userPassword.length() < 8) {

              throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码不小于8位");
          }

        // 4. 账户不包含特殊字符
         String validPattern = "^[a-zA-Z0-9_]+$";
          if (!userAccount.matches(validPattern)) {

              throw new BusinessException(ErrorCode.PARAMS_ERROR,"账户不能包含特殊字符");
          }

        // 2. 校验密码是否输入正确，要和数据库中的密文密码去对比
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
           QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("userAccount", userAccount);
             queryWrapper.eq("userPassword", encryptPassword);
              User user = userMapper.selectOne(queryWrapper);
              if (user == null) {
                  throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户不存在或者密码错误");
              }

        //3. 用户信息脱敏，隐藏敏感信息，防止数据库中的字段泄露
         user.setUserPassword(null);

        // 4. 我们要记录用户的登录态（session），将其存到服务器上（用后端 SpringBoot 框架封装的服务器 tomcat 去记录）
         request.getSession().setAttribute(userLogin, user);

        //  5. 返回脱敏后的用户信息
        return user;
    }


}





